import { post, get } from '@/utils/request'

import { showToast } from '@/utils/util'

// 统一错误处理
const handleError = (error) => {
  console.error('User API Error:', error)
  showToast(error.message || '请求失败，请稍后重试')
  throw error
}

/**
 * 用户登录
 * @param {{username: string, password: string}} credentials - 登录凭证
 * @returns {Promise<{token: string, userInfo: object}>}
 */
export const loginApi = async (credentials) => {
  if (!credentials?.username || !credentials?.password) {
    throw new Error('用户名和密码不能为空')
  }
  
  if (credentials.password.length < 6) {
    throw new Error('密码长度不能少于6位')
  }

  try {
    const res = await post('/auth/login', credentials)
    return res.data
  } catch (error) {
    handleError(error)
  }
}

/**
 * 用户注册
 * @param {{
 *   username: string,
 *   password: string,
 *   email?: string,
 *   phone?: string
 * }} userData - 用户注册数据
 * @returns {Promise<{userId: string}>}
 */
export const registerApi = async (userData) => {
  const requiredFields = ['username', 'password']
  const missingFields = requiredFields.filter(field => !userData[field])
  
  if (missingFields.length > 0) {
    throw new Error(`缺少必填字段: ${missingFields.join(', ')}`)
  }

  if (userData.password.length < 8) {
    throw new Error('密码长度不能少于8位')
  }

  if (!/[A-Z]/.test(userData.password) || !/[0-9]/.test(userData.password)) {
    throw new Error('密码必须包含数字和大写字母')
  }

  try {
    const res = await post('/auth/register', userData)
    return res.data
  } catch (error) {
    handleError(error)
  }
}

/**
 * 获取用户信息
 * @param {string} token - 用户认证token
 * @returns {Promise<UserInfo>}
 */
export const getUserInfoApi = async (token) => {
  if (!token) {
    throw new Error('缺少认证token')
  }

  try {
    const res = await get('/user/info', {
      headers: {
        Authorization: `Bearer ${token}`
      }
    })
    return res.data
  } catch (error) {
    handleError(error)
  }
}

/**
 * 用户登出
 * @param {string} token - 用户认证token
 * @returns {Promise<{success: boolean}>}
 */
export const logoutApi = async (token) => {
  if (!token) {
    throw new Error('缺少认证token')
  }

  try {
    const res = await post('/auth/logout', null, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    })
    return res.data
  } catch (error) {
    handleError(error)
  }
}

// 更新用户信息
export const updateUserInfoApi = (userData) => {
  return post('/user/update', userData)
}

// 修改密码
export const changePasswordApi = (passwordData) => {
  return post('/user/change-password', passwordData)
}